﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using ModelDto;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime;
using System.Security.Claims;
using System.Text;
using Test.Entity;
using System.Text.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json.Nodes;
using Aop.Api.Domain;
namespace Common.Achieve
{
    public class JwtHelperAppService : IJwtHelperAppService
    {
        private readonly IOptionsSnapshot<JWTTokenOption> _jwtTokenOption;

        public JwtHelperAppService(IOptionsSnapshot<JWTTokenOption> jwtTokenOption)
        {
            _jwtTokenOption = jwtTokenOption;
        }

        public (string,DateTime) CreateToken(User user)
        {
            // 1. 定义需要使用到的Claims

            string userJson = JsonSerializer.Serialize(user);
            var claims = new[]
            {
                 new Claim("User", userJson),
                 new Claim(ClaimTypes.Name, userJson),
                 new Claim("Role", user.Role),
                 new Claim(ClaimTypes.Role, user.Role),
            };
            var key = Encoding.UTF8.GetBytes(_jwtTokenOption.Value.IssuerSigningKey);
            DateTime expires = DateTime.Now.AddMinutes(_jwtTokenOption.Value.AccessTokenExpiresMinutes);
            var credentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
            var jwtSecurityToken = new JwtSecurityToken(
                                            _jwtTokenOption.Value.Issuer,     //Issuer
                                            _jwtTokenOption.Value.Audience,   //Audience
                                            claims: claims,                          //Claims,
                                            DateTime.Now,                    //notBefore
                                            expires: expires,    //expires
                                            signingCredentials: credentials               //Credentials
                                            );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return (token, expires);
        }
        public User ParseJwt(string jwt)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            try
            {
                var jwtSecurityToken = tokenHandler.ReadToken(jwt) as JwtSecurityToken;
                var user = jwtSecurityToken.Claims.FirstOrDefault(c => c.Type == "User");
                
                if (user != null)
                {
                    var userJson = JObject.Parse(user.Value);
                    string userString = userJson.ToString();
                    User user1 = JsonSerializer.Deserialize<User>(userString);
                    return user1;
                }

                return null;             
            }
            catch (SecurityTokenException ex)
            {
                // 处理验证失败的情况  
                return null;
            }
        }
    }
}
